package com.ccb.jyzx.expand.tiantouonline.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.fit.pdfdom.PDFDomTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.parsers.ParserConfigurationException;
import java.io.*;

/**
 * PDF转html
 * @projectName: extend
 * @author: jianghaolin
 * @date: 2019/11/20
 * @version: 1.0
 */
public class PDF2Html {

    static Logger logger= LoggerFactory.getLogger(PDF2Html.class);

    /**
     * PDF转HTML
     * @param filePath pdf路径
     * @param outputPath 输出html路径
     */
    public static boolean pdfToHtml(String filePath, String outputPath){
        logger.info("pad路径： " + filePath);
        logger.info("输出html路径： " + outputPath);
        boolean result = false;
        byte[] bytes = getBytes(filePath);
//        try() 写在()里面会自动关闭流
        try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outputPath)),"UTF-8"));){
            //加载PDF文档
            PDDocument document = PDDocument.load(bytes);
            PDFDomTree pdfDomTree = new PDFDomTree();
            pdfDomTree.writeText(document,out);
            //去掉生成html中的黑色边框
            deleteBorder(outputPath);
            result = true;
        } catch (Exception e) {
            logger.error("PDF转HTML失败，失败信息：" + e.getMessage());
        }
        return result;
    }

    /*
   将文件转换为byte数组
    */
    private static byte[] getBytes(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 去掉生成html中的黑色边框
     * @param files
     */
    private static void deleteBorder(String files){
        File file = new File(files);
        StringBuffer sb = new StringBuffer();
        BufferedInputStream bis = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int len = 0;
            byte[] temp = new byte[1024];
            while ((len = bis.read(temp)) != -1) {
                sb.append(new String(temp, 0, len));
            }
            String html =  sb.toString();
            html = html.replace("border:1px solid blue", "border:1px solid #ffffff");
            //删除文件

            File putFile = new File(files);
            Writer out =new FileWriter(putFile);
            out.write(html);
            out.close();
        }catch (Exception e){
            logger.error("PDF2Html.deleteBorder报错：" + e.getMessage());
        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    logger.error("PDF2Html.deleteBorder方法最后报错：" + e.getMessage());
                }
            }
        }
    }

    /**
     * 删除文件
     * @param fileName
     * @return
     */
    public static boolean delete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            logger.info("删除文件失败:" + fileName + "不存在！");
            return false;
        } else {
            return deleteFile(fileName);
        }
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                logger.info("删除单个文件" + fileName + "成功！");
                return true;
            }else {
                logger.info("删除单个文件" + fileName + "失败！");
                return false;
            }
        }else {
            logger.info("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    public static void convert(String path,String target) throws IOException {
        File file = new File(path);
        Writer output = new PrintWriter(target, "utf-8");
        try {
            convertPdf2Html(file,output);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    public static void convertPdf2Html(File input,Writer out) throws IOException, ParserConfigurationException {
        PDDocument pdf = PDDocument.load(input);
        PDFDomTree tree = new PDFDomTree();
        tree.writeText(pdf,out);
    }

}
